const san = require('san/san.js')

const swfUrl = __uri('/assets/js/video/video-js.swf')

videojs.options.flash.swf = swfUrl

const Video = san.defineComponent({
    template: `
        <div class="san-video">
            <video id="{{videoId}}" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" width="{{_width}}" height="{{height}}" poster="">
                <source s-for="v in sourcesObj" src="{{v.link}}" type='video/{{v.type}}' />
            </video>
        </div>
    `,
    attached() {
        this.nextTick(() => {
            setTimeout(() => {
                $('#' + this.data.get('videoId')).find('.vjs-big-play-button').append(`
                    <i class="iconfont icon-icon_play">&#xe760;</i>
                `)
            })
            let videoDom = document.getElementById(this.data.get('videoId'))
            const player = videojs(videoDom, {
                controls: 'control',
                preload: 'auto'
            }, function(){
            });
            const $playBtn = $('.video-js .vjs-big-play-button')
            player.on('pause', function () {
                $playBtn.show()
            })
            player.on('play', function () {
                $playBtn.hide()
            })
            player.on('ended', function () {
                $playBtn.show()
            })
        })
    },
    inited() {
        this.data.set('videoId', String(Math.random(16)).split('.')[1])
        let sources = this.data.get('sources')
        let sourcesObj = []
        for (let i = 0, len = sources.length; i < len; i++) {
            let suf = sources[i].split('.').pop().toLowerCase()
            sourcesObj.push({
                link: sources[i],
                type: suf
            })
        }
        this.data.set('sourcesObj', sourcesObj)
    },
    computed: {
        _width() {
            let width = this.data.get('width') || 0
            let videoId = this.data.get('videoId')
            if (width < 430) {
                setTimeout(() => {
                    $('#' + videoId).find('.vjs-control-bar').hide()
                })
            } else {
                setTimeout(() => {
                    $('#' + videoId).find('.vjs-control-bar').show()
                })
            }
            return width
        }
    },
    initData () {
        return {
            videoId: 'tx',
            sourcesObj: [],
            sources: ['https://cloud.video.taobao.com/play/u/1578691690/p//e/6/t/1/216258361043.mp4'],
            width: 120,
            height: 120
        }
    }
})

module.exports = Video